<template>
  <div>
      <div class="search-box">
        <!-- <div class="search-item">
          <div class="search-content">
            <el-input
              placeholder="通过商品名搜索商品,记得回车哦..."
              clearable
              @change="keywordsChange"
              style="width: 300px;margin: 0px;padding: 0px;"
              size="mini"
              :disabled="advanceSearchViewVisible"
              @keyup.enter.native="searchEmp"
              prefix-icon="el-icon-search"
              v-model="keywords">
            </el-input>
          </div>
        </div> -->
      </div>
      <div class="form-edit-btns">
        <!-- <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="searchEmp">搜索
        </el-button>
        <el-button slot="reference" type="primary" size="mini" style="margin-left: 5px"
                    @click="showAdvanceSearchView"><i
          class="fa fa-lg" v-bind:class="[advanceSearchViewVisible ? faangledoubleup:faangledoubledown]"
          style="margin-right: 5px"></i>高级搜索
        </el-button> -->

          <el-button type="primary" size="mini" icon="el-icon-plus"
                     @click="showAddEmpView">
            添加
          </el-button>
      </div>

      <el-main style="padding-left: 0px;padding-top: 0px">
        <div>
          <transition name="slide-fade">
            <div
              style="margin-bottom: 10px;border: 1px;border-radius: 5px;border-style: solid;padding: 5px 0px 5px 0px;box-sizing:border-box;border-color: #20a0ff"
              v-show="advanceSearchViewVisible">
              <el-row style="margin-top: 10px">
                <el-col :span="5">

                  <el-select v-model="search_role" placeholder="请选择">
                    <el-option
                      v-for="role in roleList"
                      :key="role.id"
                      :label="role.name"
                      :value="role.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="5" :offset="4">
                  <el-button size="mini" @click="cancelSearch">取消</el-button>
                  <el-button icon="el-icon-search" type="primary" size="mini" @click="searchEmp">搜索</el-button>
                </el-col>
              </el-row>
            </div>
          </transition>
          <el-table
            :data="emps"
            v-loading="tableLoading"
            border
            stripe
            @selection-change="handleSelectionChange"
            size="mini"
            style="width: 100%">
            <el-table-column
              type="selection"
              align="left"
              >
            </el-table-column>
             <el-table-column
              prop="cateName"
              label="商品分类"
              >
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              >
            </el-table-column>
            <el-table-column
              prop="desc"
              label="商品描述">
            </el-table-column>
            <el-table-column
              prop="price"
              label="商品价格">
            </el-table-column>
            <el-table-column
              prop="score"
              label="所需积分">
            </el-table-column>
             <el-table-column
              prop="num"
              label="商品数量">
            </el-table-column>
          
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="showEditEmpView(scope.row)" size="mini">编辑</el-button>
                <el-button type="text" @click="deleteEmp(scope.row)" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            :page-size="5"
            :current-page="currentPage"
            @current-change="currentChange"
            layout="prev, pager, next"
            :total="totalCount">
          </el-pagination>
          <div class="form-edit-btns" style="float:right">
            <el-button type="danger" size="mini" v-if="emps.length>0" :disabled="multipleSelection.length==0"
                       @click="deleteManyEmps">批量删除
            </el-button>
          </div>
        </div>
      </el-main>
    <el-dialog
      :title="dialogTitle"
      style="padding: 0px;"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
    >
        <el-form :model="emp" :rules="rules" ref="addEmpForm" style="margin: 0px;padding: 0px;">


                    <el-form-item label="商品图片:" prop="name">
                      <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        action="/file/upload"
                        name = "fileData"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="emp.img" :src="emp.img" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-form-item>
                    <div style="color:#f20;margin-left:20%">建议图片尺寸400*400</div>


                    <el-form-item label="商品名称:" prop="name">
                      <el-input prefix-icon="el-icon-edit" v-model="emp.name" size="mini"
                                placeholder="请输入商品名称"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="商品描述:" prop="phone">
                      <el-input prefix-icon="el-icon-phone" v-model="emp.phone" size="mini"
                                placeholder="电话号码..."></el-input>
                    </el-form-item> -->


                    <el-form-item label="商品描述:" prop="desc">
                      <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入商品描述"
                        v-model="emp.desc">
                      </el-input>
                    </el-form-item>

                      <el-form-item label="商品原价:" prop="originprice">
                      <el-input prefix-icon="el-icon-edit" v-model="emp.originprice" size="mini"
                                placeholder="请输入商品原价"></el-input>
                    </el-form-item>


                      <el-form-item label="商品价格:" prop="price">
                      <el-input prefix-icon="el-icon-edit" v-model="emp.price" size="mini"
                                placeholder="请输入商品价格"></el-input>
                    </el-form-item>


                      <el-form-item label="商品积分:" prop="score">
                      <el-input prefix-icon="el-icon-edit" v-model="emp.score" size="mini"
                                placeholder="请输入商品积分"></el-input>
                    </el-form-item>

                     <el-form-item label="商品数量:" prop="num">
                      <el-input prefix-icon="el-icon-edit" v-model="emp.num" size="mini"
                                placeholder="请输入商品数量"></el-input>
                    </el-form-item>

                  <el-form-item label="商品分类" prop="cate">
                    <el-select  :disabled="disabled"  v-model="emp.cate"  placeholder="请选择">
                      <el-option
                        v-for="role in roleList"
                        :key="role.cate"
                        :label="role.name"
                        :value="role.id">
                      </el-option>
                    </el-select>
                  </el-form-item>


                  <el-form-item>
                      <el-button size="mini" @click="cancelEidt">取 消</el-button>
                      <el-button size="mini" type="primary" @click="addEmp('addEmpForm')">确 定</el-button>
                  </el-form-item>

        </el-form>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        emps: [],
        keywords: '',
        props: { multiple: true },
        search_role:'',
        fileUploadBtnText: '导入数据',
        beginDateScope: '',
        faangledoubleup: 'fa-angle-double-up',
        faangledoubledown: 'fa-angle-double-down',
        dialogTitle: '',
        multipleSelection: [],
        depTextColor: '#c0c4cc',
        totalCount: -1,
        currentPage: 1,
        roleList: [],
        defaultProps: {
          label: 'name',
          isLeaf: 'leaf',
          children: 'children'
        },
        dialogVisible: false,
        disabled:true,
        tableLoading: false,
        advanceSearchViewVisible: false,
        showOrHidePop: false,
        showOrHidePop2: false,
        emp: {
          img:'',
          name: '',
          desc: '',
          originprice: '',
          price: '',
          num: '',
          cate: '',
          score: '',
          id:''
        },
        dd: '',
        rules: {
           img:[{required: true, message: '必须上传图片', trigger: 'blur'}],
          name: [{required: true, message: '必填:商品名称', trigger: 'blur'}],
          desc: [{required: true, message: '必填:商品描述', trigger: 'blur'}],
          originprice: [{required: true, message: '必填:商品原价', trigger: 'blur'}],
          price: [{required: true, message: '必填:商品价格', trigger: 'blur'}],
          num: [{required: true, message: '必填:商品数量', trigger: 'blur'}],
          cate: [{required: true, message: '必填:商品分类', trigger: 'blur'}],
          score: [{required: true, message: '必填:商品积分', trigger: 'blur'}]   
        }
      };
    },
    mounted: function () {
      this.loadEmps();
      this.initRoleData();
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.emp.img = res.url;
        //console.log(this.emp.img);
      },
      beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/gif'
          || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 20;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        return isJPG && isLt2M;
      },

      exportEmps(){
//        var iframe = document.createElement("iframe");
//        iframe.style.display = 'none';
//        iframe.src = "/employee/basic/exportEmp";
//        iframe.onload=function () {
//          document.body.removeChild(iframe);
//        }
//        document.body.appendChild(iframe);
        window.open("/student/basic/exportEmp", "_parent");
      },
      cancelSearch(){
        this.advanceSearchViewVisible = false;
        this.emptyEmpData();
        this.beginDateScope = '';
        this.loadEmps();
      },
      showAdvanceSearchView(){
        this.advanceSearchViewVisible = !this.advanceSearchViewVisible;
        this.keywords = '';
        if (!this.advanceSearchViewVisible) {
          this.emptyEmpData();
          this.beginDateScope = '';
          this.loadEmps();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      deleteManyEmps(){
        this.$confirm('此操作将删除[' + this.multipleSelection.length + ']条数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var ids = '';
          for (var i = 0; i < this.multipleSelection.length; i++) {
            ids += this.multipleSelection[i].id + ",";
          }
          this.doDelete(ids);
        }).catch(() => {
        });
      },
      deleteEmp(row){
        this.$confirm('此操作将永久删除[' + row.name + '], 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doDelete(row.id);
        }).catch(() => {
        });
      },
      doDelete(ids){
        this.tableLoading = true;
        var _this = this;
        this.postRequest("/shop/goods/delete",{ids:ids}).then(resp=> {
          _this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.$message({type: data.status, message: data.msg});
            _this.loadEmps();
          }
        })
      },

      initRoleData() {
        var _this = this;
        this.postRequest("/shop/cate/list",{pageNo:1,pageSize:20}).then(resp=> {
            //console.log(resp)
            _this.roleList = resp.data.data.arrays;
            //console.log(_this.roleList)
        })
      },


      keywordsChange(val){
        if (val == '') {
          this.loadEmps();
        }
      },
      searchEmp(){
        this.loadEmps();
      },
      currentChange(currentChange){
        this.currentPage = currentChange;
        this.loadEmps();
      },
      loadEmps(){
        var _this = this;
        this.tableLoading = true;
        this.getRequest("/shop/goods/list?pageNo=" + this.currentPage + "&pageSize=5").then(resp=> {
          this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.emps = data.data.arrays;
            _this.totalCount = data.data.count;
          }
        })
      },


      addEmp(formName){
        var _this = this;
        //console.log(formName)
        this.$refs[formName].validate((valid) => {
          //console.log(valid)
          if (valid) {
            if (_this.dd == 'update') {
              //更新
              this.tableLoading = true;
              this.postRequest("/shop/goods/update", _this.emp).then(resp=> {
                _this.tableLoading = false;
                if (resp && resp.status == 200) {
                  var data = resp.data;
                  _this.$message({type: data.status, message: data.msg});
                  _this.dialogVisible = false;
                  _this.emptyEmpData();
                  _this.loadEmps();
                }
              })
            } else {
              //添加
              //console.log(_this.emp)
              this.tableLoading = true;
              this.postRequest("/shop/goods/save", _this.emp).then(resp=> {
                  //console.log(resp)
                _this.tableLoading = false;
                if (resp && resp.status == 200) {
                  var data = resp.data;
                  _this.$message({type: data.status, message: data.msg});
                  _this.dialogVisible = false;
                  _this.emptyEmpData();
                  _this.loadEmps();
                }
              })
            }
          } else {
            return false;
          }
        });
      },
      cancelEidt(){
        this.dialogVisible = false;
        this.emptyEmpData();
      },
      showEditEmpView(row){
        //console.log(row)
        this.emptyEmpData();
        this.disabled = true;
        this.dialogTitle = "编辑";
        this.emp.img = row.img;
        this.emp.name = row.name;
        this.emp.desc = row.desc;
        this.emp.originprice  = row.originprice;
        this.emp.price = row.price;
        this.emp.num = row.num;
        this.emp.score = row.score;
        this.emp.cate = row.cate;
        this.emp.id = row.id
        this.dd = 'update'
        // delete this.emp.roles;
        this.dialogVisible = true;
      },
      showAddEmpView(){
        this.dialogTitle = "添加";
        this.emptyEmpData();
        this.dialogVisible = true;
        this.disabled = false;
        this.dd = 'add';
        var _this = this;

      },
      emptyEmpData(){
        this.emp = {
          img:'',
          name: '',
          desc: '',
          originprice: '',
          price: '',
          num: '',
          cate: '',
          score: ''
        }
      }
    }
  };
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
